package gnss

import (
	"dgo/goutils/gis"
	"fmt"
	"gitee.com/ymofen/gobase/gotask"
	"time"
)

type NtripClientUtil struct {
	clt           *NtripClient
	OnGetNmeaText func() string
	RandPosi      byte
}

func (this *NtripClientUtil) PostNmea() {
	txt := this.OnGetNmeaText()
	if len(txt) == 0 {
		return
	}
	if !this.clt.TcpClient.Connected() {
		return
	}
	nmea := gis.NewNMEA()
	nmea.ParseText(txt)
	if this.RandPosi == 1 {
		nmea.OffsetLatRand(5)
		nmea.OffsetLngRand(1)
		if nmea.GetHeight() != 0 {
			nmea.OffsetHeightRand(2)
		}
	}

	nmea.UpdateUTCTime()
	this.clt.PostBuffer(nmea.EncodeBuf())
}

func (this *NtripClientUtil) Close() {
	gotask.DefaultPatrolTask().DelTask(fmt.Sprintf("%p", this))
}

func (this *NtripClientUtil) Open() {
	gotask.DefaultPatrolTask().CheckStart()
	this.clt.Open()
	this.clt.OnAuthSuccEvent = func(sender *NtripClient, msg string) {
		this.PostNmea()
		gotask.DefaultPatrolTask().AddTask(fmt.Sprintf("%p", this), time.Second*10, func(id interface{}, args ...interface{}) {
			this.PostNmea()
		})
	}
}

func (this *NtripClientUtil) GetClient() *NtripClient {
	return this.clt
}

func (this *NtripClientUtil) SetNmea(nmeaText string) {
	this.OnGetNmeaText = func() string {
		return nmeaText
	}
}

func NewNtripClientUtil(connstring string) *NtripClientUtil {
	conf := ParseNtripClientConnectString(connstring)
	rval := &NtripClientUtil{}
	clt := NewNtripClient()
	rval.clt = clt
	if len(conf.Addr) > 0 {
		clt.SetRemoteAddress(conf.Addr)
		clt.SetNtripClientUser(conf.User, conf.Pass)
		clt.SetRequestMountPoint(conf.MountPoint)
		rval.SetNmea(conf.NMEA)
	}
	return rval
}
